package com.atguigu.gulimall.product.service.impl;

import com.atguigu.common.constant.ProductConstant;
import com.atguigu.common.to.SkuReductionTo;
import com.atguigu.common.to.SpuBoundTo;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.product.dao.SpuInfoDao;
import com.atguigu.gulimall.product.entity.*;
import com.atguigu.gulimall.product.feign.CouponFeignService;
import com.atguigu.gulimall.product.feign.SearchFeignService;
import com.atguigu.gulimall.product.feign.WareFeignService;
import com.atguigu.gulimall.product.service.*;
import com.atguigu.gulimall.product.vo.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private SpuImagesService imagesService;
    @Autowired
    private SpuInfoDescService descService;
    @Autowired
    private ProductAttrValueService productAttrValueService;
    @Autowired
    private SkuInfoService skuInfoService;
    @Autowired
    private SkuImagesService skuImagesService;
    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    private BrandService brandService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private WareFeignService wareFeignService;
    @Autowired
    private SearchFeignService searchFeignService;

    @Autowired
    private CouponFeignService couponFeignService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void save(SkuSaveVo vo) {
//        1、保存spu基本信息
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(vo,spuInfoEntity);
        Long brandId = vo.getBrandId();
        Long catalogId = vo.getCatalogId();

        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.save(spuInfoEntity);
        Long spuId = spuInfoEntity.getId();

//        2、保存spu图片集
        List<String> images = vo.getImages();
        imagesService.saveImages(spuId,images);
//        3、保存spu描述图片 pms_spu_images
        List<String> decript = vo.getDecript();
        descService.saveDecript(spuId,decript);
//        4、保存spu的规格参数pms_product_attr_value
        List<BaseAttrs> baseAttrs = vo.getBaseAttrs();
        productAttrValueService.saveBaseAttr(spuId,baseAttrs);
//        5、保存spu的积分信息 远程服务调用
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        Bounds bounds = vo.getBounds();
        BeanUtils.copyProperties(bounds,spuBoundTo);
        spuBoundTo.setSpuId(spuId);
        R r = couponFeignService.saveBound(spuBoundTo);
        if (r.getCode()!=0){
            log.error("远程保存积分信息失败");
        }

//        6、保存spu对应的所有sku信息
        List<Skus> skus = vo.getSkus();
//        skus.stream().map(sku->{
//            //找到默认图片的路径
//            String defaultImg="";
//            List<Images> skuImages = sku.getImages();
//            for (Images skuImage : skuImages) {
//                if (skuImage.getDefaultImg()==1){
//                    defaultImg=skuImage.getImgUrl();
//                }
//            }
//            //1、sku的基本信息
//            SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
//            BeanUtils.copyProperties(sku,skuInfoEntity);
////            private String skuName;
////            private BigDecimal price;
////            private String skuTitle;
////            private String skuSubtitle;
//            skuInfoEntity.setCatalogId(catalogId);
//            skuInfoEntity.setBrandId(brandId);
//            skuInfoEntity.setSaleCount(0L);
//            skuInfoEntity.setSkuDefaultImg(defaultImg);
//            skuInfoEntity.setSpuId(spuId);
//            skuInfoService.save(skuInfoEntity);
//
//            //        2、保存图片信息
//            List<SkuImagesEntity> skuImagesEntities = skuImages.stream().map(img -> {
//                SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
//                BeanUtils.copyProperties(img, skuImagesEntity);
//                skuImagesEntity.setSkuId(skuInfoEntity.getSkuId());
//                return skuImagesEntity;
//            }).collect(Collectors.toList());
//            skuImagesService.saveBatch(skuImagesEntities);
//            //        3、sku的销售属性值
//            List<Attr> attrs = sku.getAttr();
//            List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attrs.stream().map(attr -> {
//                SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
//                BeanUtils.copyProperties(attr, skuSaleAttrValueEntity);
//                skuSaleAttrValueEntity.setSkuId(skuInfoEntity.getSkuId());
//                return skuSaleAttrValueEntity;
//            }).collect(Collectors.toList());
//            skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);
//
////        4、sku的优惠满减信息，跨库了 sms_sku_ladder sms_sku_full_reduction sms_member_price
//            SkuReductionTo skuReductionTo = new SkuReductionTo();
//            BeanUtils.copyProperties(sku,skuReductionTo);
//            R r1 = couponFeignService.saveReduction(skuReductionTo);
//            if (r1.getCode()!=0){
//                log.error("远程保存折扣信息失败");
//            }
//
//            return sku;
//        });

//

        skus.forEach(sku->{
            //找到默认图片的路径
            String defaultImg="";
            List<Images> skuImages = sku.getImages();
            for (Images skuImage : skuImages) {
                if (skuImage.getDefaultImg()==1){
                    defaultImg=skuImage.getImgUrl();
                }
            }
            //1、sku的基本信息
            SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
            BeanUtils.copyProperties(sku,skuInfoEntity);
//            private String skuName;
//            private BigDecimal price;
//            private String skuTitle;
//            private String skuSubtitle;
            skuInfoEntity.setCatalogId(catalogId);
            skuInfoEntity.setBrandId(brandId);
            skuInfoEntity.setSaleCount(0L);
            skuInfoEntity.setSkuDefaultImg(defaultImg);
            skuInfoEntity.setSpuId(spuId);
            skuInfoService.save(skuInfoEntity);

            //        2、保存图片信息skuImagesEntity
            List<SkuImagesEntity> skuImagesEntities = skuImages.stream().map(img -> {
                SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                BeanUtils.copyProperties(img, skuImagesEntity);
                skuImagesEntity.setSkuId(skuInfoEntity.getSkuId());
                return skuImagesEntity;
            }).filter(img->{
                return !StringUtils.isEmpty(img.getImgUrl());
            }).collect(Collectors.toList());
            skuImagesService.saveBatch(skuImagesEntities);
            //        3、sku的销售属性值
            List<Attr> attrs = sku.getAttr();
            List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attrs.stream().map(attr -> {
                SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                BeanUtils.copyProperties(attr, skuSaleAttrValueEntity);
                skuSaleAttrValueEntity.setSkuId(skuInfoEntity.getSkuId());
                return skuSaleAttrValueEntity;
            }).collect(Collectors.toList());
            skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);

//        4、sku的优惠满减信息，跨库了 sms_sku_ladder sms_sku_full_reduction sms_member_price
            SkuReductionTo skuReductionTo = new SkuReductionTo();
            skuReductionTo.setSkuId(skuInfoEntity.getSkuId());
            BeanUtils.copyProperties(sku,skuReductionTo);
            if (skuReductionTo.getFullCount()>0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal("0"))==1){

                R r1 = couponFeignService.saveReduction(skuReductionTo);
                if (r1.getCode()!=0){
                    log.error("远程保存折扣信息失败");
                }
            }
        });

    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();
        String key=(String)params.get("key");
        if (!StringUtils.isEmpty(key)){
            wrapper.and(w->{
                w.eq("id",key).or().like("spu_name",key);
            });
        }

        String status=(String)params.get("status");
        if (!StringUtils.isEmpty(status)){
            wrapper.eq("publish_status",status);
        }

        String brandId=(String)params.get("brandId");
        if (!StringUtils.isEmpty(brandId) ){
            wrapper.eq("brand_id",brandId);
        }

        String catelogId=(String)params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId) ){
            wrapper.eq("catalog_id",catelogId);
        }
        IPage<SpuInfoEntity> page = this.page(new Query<SpuInfoEntity>().getPage(params), wrapper);

        return new PageUtils(page);
    }

    @Override
    public void spuInfoUp(Long spuId) {

        //找到需要上架的所有SKU
        List<SkuInfoEntity> skuInfoEntities=skuInfoService.getSkusBySpuId(spuId);

        //找到可以快速检索的ProductAttr（规格参数）
        List<ProductAttrValueEntity> productAttrValueEntities=productAttrValueService.getAttrsWithSerachBySpuId(spuId);
        //TODO 找到每一个SKU中的可以快速检索的attr
        List<SkuEsModel.Attr> attrs = productAttrValueEntities.stream().map(item -> {
            SkuEsModel.Attr attr = new SkuEsModel.Attr();
            BeanUtils.copyProperties(item, attr);
            return attr;
        }).collect(Collectors.toList());
        //获得需要skuID集合
        List<Long> skuIds = skuInfoEntities.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
        Map<Long, Boolean> hasStockMap =null;
        try {
            //查询每个sku是否都有库存
            List<SkuHasStockVo> data = wareFeignService.getSkuHasStockVoBySkuIds(skuIds);
            hasStockMap = data.stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, item -> item.getHasStock()));
            System.out.println(hasStockMap);
        }catch (Exception e){
            log.error("远程链接ware服务失败");
            System.out.println(e);
        }

        //获取到 库存信息
        Map<Long, Boolean> finalHasStockMap = hasStockMap;
        //将skuInfoEntity封装进SkuEsModel
        List<SkuEsModel> skuEsModels=skuInfoEntities.stream().map(skuInfoEntity -> {
            SkuEsModel skuEsModel = new SkuEsModel();
            BeanUtils.copyProperties(skuInfoEntity,skuEsModel);
            //skuPrice  skuImg  hasStock(需要查 ware) hotScore  brandName brandImg catalogName attrs
            skuEsModel.setSkuPrice(skuInfoEntity.getPrice());
            skuEsModel.setSkuImg(skuInfoEntity.getSkuDefaultImg());
            //TODO hasStock(需要查 ware) 进行远程调用
            if (finalHasStockMap ==null){
                skuEsModel.setHasStock(true);
            }else {
                skuEsModel.setHasStock(finalHasStockMap.get(skuEsModel.getSkuId()));
            }


            skuEsModel.setHotScore(0L);

            //TODO 根据brandid 查询brandName brandImg catalogName
            BrandEntity brandEntity = brandService.getById(skuInfoEntity.getBrandId());
            skuEsModel.setBrandName(brandEntity.getName());
            skuEsModel.setBrandImg(brandEntity.getLogo());
            CategoryEntity categoryEntity = categoryService.getById(skuEsModel.getCatalogId());
            skuEsModel.setCatalogName(categoryEntity.getName());

            skuEsModel.setAttrs(attrs);


            return skuEsModel;
        }).collect(Collectors.toList());

        //将skuEsModels发送到search服务 进行存储
        R r = searchFeignService.searchSaveProduct(skuEsModels);
        if (r.getCode()==0){
            baseMapper.updateStatusUp(spuId, ProductConstant.StatusEnum.PRODUCT_UP.getCode());
        }
    }

    @Override
    public SpuInfoEntity getSpuInfoBySkuId(Long skuId) {
        SkuInfoEntity byId = skuInfoService.getById(skuId);
        Long spuId = byId.getSpuId();
        SpuInfoEntity spuInfoEntity = getById(spuId);
        return spuInfoEntity;
    }

}